import re
import sys
from geopy import distance

on_linux = 0;

def MakeBox(coords,radius):
	# This function will take a coordinate point and generate a bounding box with a radius
	# expressed in miles
	kmdistance = distance.kilometers(radius,0,0)
	
	latn,junk = distance.vincenty_destination(coords,0,kmdistance)
	lats,junk = distance.vincenty_destination(coords,180,kmdistance)
	junk,longe = distance.vincenty_destination(coords,90,kmdistance)
	junk,longw = distance.vincenty_destination(coords,270,kmdistance)
	
	box = (latn, lats, longe, longw)
	return box
	

# Open the Block Group file for reading
if on_linux==1:
	bgfile = open("block_geocodes.csv","r")
	outfile = open("NewBlockGroupMatches_newBG.csv","w")
else:
	bgfile = open("block_geocodes.csv","r")
	outfile = open("NewBlockGroupMatches_newBG.csv","w")

bgfile.readline()   # reads in the header row

bgDict = {}
for line in bgfile:
	line = line.rstrip('\n')
	myList = line.split(',')
	fips = myList[0] + myList[1] + myList[2] + myList[3]
	coordlat = float( myList[4] )
	coordlong = float( myList[5] )
	bgDict[fips] = [ coordlat, coordlong ]

print len(bgDict)
bgfile.close()

if on_linux==1:
	#tufile = open("fordistance.csv","r")
	tufile = open("block_geocodes.csv","r")
else:
	#tufile = open("fordistance.csv","r")
	tufile = open("block_geocodes.csv","r")

tufile.readline()  # reads in the header row

counter = 0
for line in tufile:
	line = line.rstrip('\n')
	counter = counter + 1
	thislist = line.split(',')
	thisgeo = ( float(thislist[4]) , float(thislist[5]) )
	outfile.write( thislist[0] + thislist[1] + thislist[2] + thislist[3] )
	
	try:
		bestbox = MakeBox(thisgeo,1.1)  # create a box with a sides equal to 2.2 miles as a starting box
	except:
		print counter, thisgeo
		sys.exit()
		
	for blockgrp in bgDict:
		bglat = bgDict[blockgrp][0]
		bglong = bgDict[blockgrp][1]
		if ((bglat<bestbox[0]) and (bglat>bestbox[1]) and (bglong<bestbox[2]) and (bglong>bestbox[3])):
			# block group is within the best box
			
			if ( (thisgeo[0]==bglat) and (thisgeo[1]==bglong) ):
				outfile.write( "\t" + blockgrp + ",0.0000" )
			else:
				thisdistance = distance.distance(thisgeo,(bglat, bglong)).miles
				if (thisdistance<=1):
					outfile.write( "\t" + blockgrp + "," + str( thisdistance ) )
				
	outfile.write( "\n" )
	 
	if ( int(counter/1000)*1000==counter):
		print "Doing observation ", counter
		#counter = counter - 1000
				
tufile.close()	
outfile.close()

